﻿Imports System.Data.SqlClient
Public Class frm_bkrs

    Dim path As String
    Dim save As New SaveFileDialog
    Private Sub cmd_mo_Click(sender As System.Object, e As System.EventArgs) Handles cmd_mo.Click

        save.FileName = "backup" + DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + ".Bak"
        save.Filter = "File(*.bak)|*.bak"
        If (save.ShowDialog() = DialogResult.OK) Then
            txt_dgdan.Text = save.FileName
            path = System.IO.Path.GetFullPath(save.FileName)
        End If
    End Sub

    Private Sub cmd_backup_Click(sender As System.Object, e As System.EventArgs) Handles cmd_backup.Click
        If txt_dgdan.Text = "" Then
            MsgBox("Xin vui lòng chọn đường dẫn")
            Exit Sub
        End If
        Dim kiemtra As String = txt_dgdan.Text
        If kiemtra.Substring(0, 1) = "C" Then
            MsgBox("không thể lưu vào ổ C")
            cmd_mo_Click(sender, e)
            Exit Sub
        End If
        Try
            Dim cmd = New SqlCommand("USE master; BACKUP DATABASE DBQuanLyTrungTamTinHoc TO DISK = '" & path.ToString & "'", conn)
            'conn.Open()
            cmd.ExecuteNonQuery()
            MsgBox("backup file thành công")
            'conn.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
            'conn.Close()
        End Try

    End Sub

    Private Sub cmd_restore_Click(sender As System.Object, e As System.EventArgs) Handles cmd_restore.Click
        Dim open As New OpenFileDialog
        open.FileName = "backup" + DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + ".Bak"
        open.Filter = "File(*.bak)|*.bak"

        If (open.ShowDialog() = DialogResult.OK) Then
            txt_dgdan.Text = save.FileName
            path = System.IO.Path.GetFullPath(open.FileName)
        End If
        Try
            Dim cmd = New SqlCommand("USE master ALTER DATABASE DBQuanLyTrungTamTinHoc SET SINGLE_USER WITH ROLLBACK IMMEDIATE  RESTORE DATABASE DBQuanLyTrungTamTinHoc FROM DISK = '" & path & "' ALTER DATABASE DBQuanLyTrungTamTinHoc SET MULTI_USER ;", conn)
            'conn.Open()
            cmd.ExecuteNonQuery()
            MsgBox("Restore database thành công")
        Catch ex As Exception
            MsgBox(ex.Message)
            'conn.Close()
        End Try

    End Sub
End Class